<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CContractForm">
          <a-row>
						<a-col :span="12">
							<a-form-item label="合同编号" v-bind="validateInfos.contractNo" id="CContractForm-contractNo" name="contractNo">
								<a-input v-model:value="formData.contractNo" placeholder="请输入合同编号" style="width: 68%"   allow-clear ></a-input>
								<a-button v-if="formData.id==='' " type="primary" style="margin-left: 8px;" @click="generateContractNumber">生成合同编号</a-button>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="合同名称" v-bind="validateInfos.name" id="CContractForm-name" name="name">
								<a-input v-model:value="formData.name" placeholder="请输入合同名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12" >
							<a-form-item label="项目" v-bind="validateInfos.projectId" id="CContractForm-projectId" name="projectId">
								 <j-dict-select-tag showSearch="true" :trigger-change="true" @change="projectOnChange"  v-model:value="formData.projectId" dictCode="c_project_application,project_name,id" placeholder="请选择项目"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12" v-if="isProject===true">
							<a-form-item label="子项目" v-bind="validateInfos.subProjectId" id="CContractForm-subProjectId" name="subProjectId">
								 <j-dict-select-tag showSearch="true"
                                    v-model:value="formData.subProjectId"
                                    :dictCode="subProjectdictCode"
                                    placeholder="请选择子项目"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="合同金额" v-bind="validateInfos.contractAmount" id="CContractForm-contractAmount" name="contractAmount">
								<a-input-number  @blur="setContractAmount()" v-model:value="formData.contractAmount" placeholder="请输入合同金额" style="width: 100%" />
							</a-form-item>
						</a-col>

						<a-col :span="12">
							<a-form-item label="税率%" v-bind="validateInfos.taxRate" id="CContractForm-taxRate" name="taxRate">
								<a-input-number @blur="amountCalculator()" v-model:value="formData.taxRate" max="100" min="0" placeholder="请输入税率" style="width: 10%" />%
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="是否含税价" v-bind="validateInfos.taxIncluded" id="CContractForm-taxIncluded" name="taxIncluded">
								<j-switch @blur="amountCalculator()" v-model:value="formData.taxIncluded"  ></j-switch>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="含税价" v-bind="validateInfos.taxIncludingPrice" id="CContractForm-taxIncludingPrice" name="taxIncludingPrice">
								<a-input-number disabled="true" @blur="amountCalculator()" v-model:value="formData.taxIncludingPrice" placeholder="请输入含税价" style="width: 100%" />
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="质保金(含税)" v-bind="validateInfos.warrantyPrice" id="CContractForm-warrantyPrice" name="warrantyPrice">
                <a-input-number   v-model:value="formData.warrantyPrice" placeholder="请输入质保金(含税)" style="width: 100%" />
              </a-form-item>
            </a-col>

						<a-col :span="12">
							<a-form-item label="合同日期" v-bind="validateInfos.contractDate" id="CContractForm-contractDate" name="contractDate">
								<a-date-picker placeholder="请选择合同日期"  v-model:value="formData.contractDate" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="合同文件" v-bind="validateInfos.contractFile" id="CContractForm-contractFile" name="contractFile">
								<j-upload v-model:value="formData.contractFile"  dragger="true"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"  ></j-upload>
							</a-form-item>
						</a-col>
            	<a-col :span="12">
							<a-form-item label="备注" v-bind="validateInfos.remark" id="CContractForm-remark" name="remark">
								<a-textarea v-model:value="formData.remark" :rows="4" placeholder="请输入备注" />
							</a-form-item>
						</a-col>


          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../CContract.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  const subProjectdictCode = ref('c_sub_project,sub_project_name,id,project_id=0');
    import {encryptByBase64} from "@/utils/cipher";
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const contractAmount = ref(Number)
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    contractNo: '',   
    projectId: '',   
    subProjectId: '',   
    contractAmount: undefined,
    contractDate: '',   
    contractFile: '',
    taxIncludingPrice: '',
    taxIncluded: '',
    taxRate: '',
    name: '',
    remark: '',
    warrantyPrice: '',
  });
  const { createMessage } = useMessage();
  const isProject = ref(true)
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    contractNo: [{ required: true, message: '请输入合同编号!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  	function generateContractNumber() {
       formData.contractNo = generateContractNumbermethod()
    }
    	function generateContractNumbermethod() {
	   // 示例：生成一个简单的合同编号
	   const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');
	   const randomString = Math.random().toString().substring(2, 6);
	   return `YC-${date}-${randomString}`;
	   
	}
  /**
   * 新增
   */
  function add(record) {
    edit(record);
  }


  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
    if(record != undefined){
      if(record.projectId){
        projectOnChange(record.projectId)
      }
      if(record.isProject != undefined && record.isProject != null){
        isProject.value = record.isProject
      }
    }

	
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
  
  function projectOnChange(value){
	 subProjectdictCode.value = 'c_sub_project,sub_project_name,id,project_id='+value
  }

  /**
   * 标记合同价格
   */
  function setContractAmount(){
    contractAmount.value = formData.contractAmount
    amountCalculator()
  }

  function amountCalculator(){

/*    是否包税价===否
        合同金额 *（1+税率）=含税价
    是否包税价===是
        含税价 = 合同金额
        合同金额 =  含税价/（1-税率）*/
    console.info(formData.contractAmount)//合同金额
    console.info(formData.taxIncluded)//合同价是否含税价
    console.info(formData.taxRate)//税率
    console.info(formData.taxIncludingPrice)//含税价

    if(formData.taxRate != undefined && formData.taxRate != ""){

      if(formData.taxIncluded ==="Y"){//合同价包税价
        formData.taxIncludingPrice = contractAmount.value
        formData.contractAmount = ((formData.taxIncludingPrice * (100-formData.taxRate)) /100).toFixed(2)
      }else {
        formData.taxIncludingPrice = ((contractAmount.value * (100 + formData.taxRate ))/100).toFixed(2)
        formData.contractAmount = contractAmount.value
      }


    }





  }


  defineExpose({
    add,
    edit,
    submitForm,
	subProjectdictCode,
	projectOnChange,
  generateContractNumbermethod,
  generateContractNumber,
    isProject,
    amountCalculator,
    contractAmount

  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
